import { gzip, inflate } from 'pako'

export const uint8ArrayToBase64 = uint8Array => {
  const data = new Uint8Array(uint8Array)
  const chunkSize = 65536 // 每个小块的大小
  let baseJson = ''
  for (let i = 0; i < data.length; i += chunkSize) {
    const chunk = data.slice(i, i + chunkSize)
    baseJson += String.fromCharCode.apply(null, chunk)
  }
  return btoa(baseJson) // 将ArrayBuffer类型使用btoa()函数转化为base64编码字符串
}

/**
 * 压缩Json
 * json: String 需要压缩的json
 */
export const zip = json => {
  const binaryString = gzip(json, { to: 'string' })
  return uint8ArrayToBase64(binaryString)
}

/**
 * 解缩Json
 * json: String 需要解缩的json
 */
export const unzip = base64Json => {
  if (!base64Json) return base64Json
  const baseData = atob(base64Json)
  const charData = baseData.split('').map(function (x) { return x.charCodeAt(0) })
  return inflate(new Uint8Array(charData), { to: 'string' })
}